package com.whucke.im.vo;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 接口返回信息
 *
 * @author Zhang Peng
 * @since 2019/2/20 10:09
 */
public class JsonResult {

    /**
     * 返回状态
     * true-成功，false-失败
     */
    private boolean status = false;

    /**
     * 返回信息
     * 一般在返回失败的时候附带失败信息
     */
    private String msg;

    /**
     * 返回数据
     */
    private Object body;

    public JsonResult() {
    }

    public JsonResult(boolean status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public JsonResult(Object body) {
        this.body = body;
    }

    public JsonResult(boolean status, String msg, Object body) {
        this.status = status;
        this.msg = msg;
        this.body = body;
    }

    public String toJson() {
        return JSON.toJSONString(this);
    }


    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getBody() {
        return body;
    }

    public void setBody(Object body) {
        this.body = body;
    }

    /**
     * 把body转换成map
     * 注意:当返回结果为多对象嵌套json字符串时，转换map有可能会失败
     *
     * @return
     */
    public Map<String, String> bodyToMap() {
        if (this.body == null) {
            return new HashMap<>();
        }
        return JSON.parseObject(body.toString(), Map.class);
    }

    /**
     * 命令行打印结果
     */
    public void printResult() {
        if (!StringUtils.isEmpty(this.msg)) {
            System.out.printf("返回: %s \r\n", this.msg);
        }
    }
}
